jQuery(function ($) {
    var File = Cofe.Models.File;
    var Folder = Cofe.Models.Folder;

    var constructEntry = function(item) {
            if (item.basetype == "Folder") {
                 return Folder.init(item); 
                 }
             else if (item.basetype == "File") {
                return File.init(item);
            }
            else throw "error : wrong itemType";

        };

    var ContentListItem = Spine.Controller.create({

        elements: {           
            ".workIndicator": "workIndicator"
        },

        events: {
            "click .label": "click"
        },
        proxied: ["render", "remove"],

        init: function () {
            

        },

       

        render: function (item) {
            if (item) this.item = item;
            var entry = constructEntry(this.item);
            this.el.html(this.template(entry));
            return this;
        },

        template: function (item) {
            return ($("#contentItemTemplate").tmpl(item));
        },

        remove: function () {
            this.el.remove();
        },

        click: function () {
            if (this.item.basetype == "Folder")
                this.App.trigger("pathChanged", "contentListItem", this.item.path); 
            else {
                var entry = constructEntry(this.item);
                if (entry.links['download'] != undefined)
                    window.open(entry.links['download'].uri);
            }
        }
    });

    var ContentList = Spine.Controller.create({
        elements: {
            ".contentList": "contentList"
        },

        events: {

        },

        proxied: ["addOne", "addAll", "refresh"],

        init: function (path) {
                       

//            if (window.location.hash != ""){
//                this.changePath(decodeURI(window.location.hash.slice(1)));                
//            } else { this.changePath(""); }
//            $(window).bind("hashchange", this.proxy(function(event) {
//                this.changePath(decodeURI(window.location.hash.slice(1)));                
//            }));
            this.App.bind("pathChanged", this.proxy(function(sender, path) {
                console.log("ContentList : " +  sender + " raised pathChanged " + path);
                this.changePath(path);
            }));
            this.App.bind("refresh", this.refresh);
        },        
        refresh : function() {
            this.el.empty();
            this.entryList.fetch();
        },
        
        changePath: function (path) {            
            if (this.path != path) {              

            this.path = path;        
             Cofe.Models.EntryList.unattachEvents(this.entryList, this.addAll, this.ajaxError);
             this.entryList = Cofe.Models.EntryList.lookupOrCreate(path, this.addAll, this.ajaxErr);
             this.addAll();
//             this.entryList.bind("refresh", this.addAll);
//             this.entryList.bind("ajaxError", this.ajaxErr);
             
//             if (this.entryList.status == undefined) {                 
//                this.refresh(); //not loaded (just created) 
//             } else {
//                this.addAll();
//             }

//            if (Cofe.Models.EntryList.exists(path)) {
//                this.entryList = Cofe.Models.EntryList.select(function (el) { return el.id == path; })[0];
//                this.entryList.bind("refresh", this.addAll);
//                this.entryList.bind("ajaxError", this.ajaxErr);
//                this.addAll();
//            } else 
//            { 
//                var prevEntryList = this.entryList;
//                //Unbind events of previous entry list.
//                if (prevEntryList != undefined && prevEntryList.unbind != undefined){
//                    prevEntryList.unbind("refresh", this.addAll);
//                    prevEntryList.unbind("ajaxError", this.ajaxErr);
//                }

//                this.entryList = Cofe.Models.EntryList.init({ path : path });
//                this.entryList.bind("refresh", this.addAll);
//                this.entryList.bind("ajaxError", this.ajaxErr);
//                
//                this.refresh(); 
//            }          
            }
        },      

        ajaxErr : function (xhr, s, e) {
                    window.alert("error when fetching " + path)
                },

        addOne: function (item) {
            var entryItem = ContentListItem.init({item: item});
            this.el.append(entryItem.render().el);
        },

        addAll: function () {
            this.el.empty();
            if (this.entryList != undefined && this.entryList.entries != undefined) {
            var sortedEntries = this.entryList.entries.slice();
            sortedEntries.sort(function(a,b){
                if (a.basetype != b.basetype)
                    if (a.basetype == "Folder")
                        return -1;
                    else return 1;
                return (a.path < b.path) ? -1 : 1;
            });
            
            $.each(sortedEntries, this.proxy(function (i, entry) { this.addOne(entry); }))                
           }
        }
});

window.ContentList = ContentList;

})